<?php
/**
 * mock_fmw_api
 * CegidController.php
 * @author: Heze
 * Date: 2024/7/17 18:15
 */

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class CegidController extends Controller
{
    protected $baseUrl = '/api/cegid/dev/event';

    protected $requestParams = [];

    public function index(Request $request)
    {
        $url = $request->get('s');
        $methodUrl = trim(str_replace($this->baseUrl, '', $url), '/');
        if (!empty($methodUrl)) {
            $method = str_replace(['/', '-'], '_', $methodUrl);
        } else {
            return [];
        }

        if (!method_exists($this, $method)) {
            echo sprintf("[%s] mock function not exists", $method);
            exit;
        }
        $this->requestParams = json_decode($request->get('360buy_param_json'), true);

        return $this->$method($request);
    }

    public function bbc()
    {
        return [
            'msg' => '',
            'status' => 'success',
        ];
    }

    public function pioneer()
    {
        return [
            'msg' => '',
            'status' => 'success',
        ];
    }

    public function laofoye()
    {
        return response([
            "code" => "REMOTE_RESPONSE_ERROR",
            "message" => "百盛接口返回错误",
            "sub_code" => "-1",
            "sub_msg" => "SH20120250730622168-1保存单据失败,渠道调拨单据重复！"
        ], 400);


        return [
            "success" => 1,
            "noticeSn" => "xxx",
            "sourceOrderSn" => "xxx",
            "message" => ""
        ];
    }

    public function api_sales_data()
    {
        return [
            'SendMessageResponse' => [
                'ResponseMetadata' => [
                    'RequestId' => Str::random(16),
                ],
                'SendMessageResult' => [
                    "MD5OfMessageAttributes" => null,
                    "MD5OfMessageBody" => "3cebc7685a3d57ef1e9ce139a3bc7fbb",
                    "MD5OfMessageSystemAttributes" => null,
                    "MessageId" => "b77eb835-5b1c-4665-a7f1-900fc8dbb7b2",
                    "SequenceNumber" => null
                ],
            ]
        ];
    }

    public function api_qimen_api_stocks(Request $request)
    {
        $result = [];
        $skuCodes = array_filter(explode(',', $request->get('skuCodes', '')));
        $ownerCode = $request->get('ownerCode', []);
        foreach ($skuCodes as $skuCode) {
            $result[$skuCode] = [
                'skuCode' => $skuCode,
                'warehouseStocks' => $this->_mockStorageStock($ownerCode),
            ];
        }

        return $result;
    }

    public function api_qimen_api_shipping_notices(Request $request)
    {
        $notices = $request->get('notices', '');
        $sourceOrderSns = $request->get('sourceOrderSns', []);

        return [
            "noticeSn" => $notices[0]['noticeSn'] ?? 'noticeSn',
            "sourceOrderSns" => $sourceOrderSns,
            "wmsOrderCodes" => [
                'MOCK_DCFH' . time()
            ]
        ];

//        return response([
//            "message" => "奇门接口返回错误",
//            "code" => "REMOTE_RESPONSE_ERROR",
//            "sub_code" => "operation.failed",
////            "sub_msg" => "旺店通WMS返回：发货单推送失败6977665611619商品可发库存不足，请联系仓库人员到wms系统【库存-库存管理】界面核对OMS可支配库存是否充足。",
////            "sub_msg" => "请求失败:当前SKU BU库存不存在，请核实 - 当前SKU BU库存不存在,请核实。merchantId:2215950968981, scItemId:761652329041, itemCode: 2024010912000001, storeCode:JIX235, channelCode:DEFAULT, bizUnitId:DEFAULT, invType:1",
//            "sub_msg" => '发货失败！自定义错误！',
//        ], 400);
    }

    public function api_qimen_api_cancel_shipping_notices(Request $request)
    {
        return [];
    }

    public function mercedesBenzToken(Request $request)
    {
        return [
            "access_token" => 'benz_token_' . date('YmdHis') . Str::random(10),
            "instance_url" => "https://int.crm-cn.mercedes-benz.com.cn/leadserviceapi",
            "token_type" => "Bearer",
            "issued_at" => 1717482747264
        ];
    }

    public function mercedesBenzLeadService(Request $request)
    {
//        return response([
//            'errors' => [
//                [
//                    "errorCode" => "401",
//                    "message" => "Authentication failed.",
//                    "leadIds" => null
//                ]
//            ]
//        ], 401);


//        $errorData = [
//            "success" => false,
//            "sourceId" => "20250729007",
//            "createdTime" => "2024-06-04T06:30:42Z",
//            "errors" => [
//                [
//                    "errorCode" => "40001008",
//                    "message" => "CRM internal errors:[Not found dealer with ND Code: '测试经销商' or GS Code: ''].",
//                    "leadIds" => null
//                ]
//            ]
//        ];
//
//        return [$errorData];


        $data = [
            "success" => true,
            "sourceId" => "432730000000065326209767499",
            "leadId" => "a0620244065564BN9V8M",
            "accountId" => null,
            "createdTime" => "2024-06-04T06:30:42Z",
            "errors" => []
        ];

        return [$data];
    }


    private function _mockStorageStock($ownerCode)
    {
        $result = [];
        $storages = ['TEST_CAINIAO', 'TEST_QM_CAINIAO', 'QMTTX_STORAGE', 'QMGFS_STORAGE'];
        foreach ($storages as $storage) {
            $result[] = [
                "ownerCode" => $ownerCode,
                "warehouseCode" => $storage,
                "quantity" => rand(100, 999)
            ];
        }

        return $result;
    }

    public function casio_psi(Request $request)
    {
        return [
            'errcode' => 0,
            'errmsg' => '',
        ];
    }

    public function pec(Request $request)
    {
        return response([
            "error" => 1,
            "msg" => "已发货的订单不能重复发货"
        ], 400);
    }

    public function youliao(Request $request)
    {
        return response([
            "sub_message" => "",
            "message" => "Call to undefined relationship [item] on model [App\\Modules\\Order\\Models\\AfterSaleReplyItem].",
            "code" => 400,
            "sub_code" => "ERROR"
        ], 400);
    }

    public function almm(Request $request)
    {
        $method = $request->get('method', '');

        if ($method == 'taobao.universalbp.new.bidword.update') {
            $bidwords = $request->get('word_update_request_v_o', '');
            $bidwordList = json_decode($bidwords, true)['bidword_list'] ?? [];

            return [
                'universalbp_new_bidword_update_response' => [
                    'top_result' => [
                        'info' => [],
                        'word_command_v_o_top_bulk_data' => [
                            'count' => count($bidwordList),
                            'word_command_v_o_list' => [
                                'word_command_v_o' => $bidwordList
                            ],
                        ],
                    ],
                ],
            ];
        }

        return response([], 200);
    }
}
